import ROOT from '@/config/index'

/**
 * 封装请求
 * @param {String} param.base - 域名
 * @param {String} param.url - 接口地址
 * @param {Object} param.data - 入参
 * @param {string} param.method='get' - 请求方式
 * @param {Object} param.header - header参数
 * @param {Object} param.loading=false - 是否显示loading
 * @param {Boolean} param.isHideToast=false - 是否显示错误信息
 * @returns {Promise<unknown>}
 */

const httpArr = []

function http(param) {
  const isHideToast = param.isHideToast || false // 是否隐藏错误提示
  return new Promise((resolve, reject) => {
    httpArr.push(param)
    if (param.loading) {
      uni.showLoading({
        title: '加载中'
      })
    }
    const token = uni.getStorageSync('token') || ''
    const userInfo = uni.getStorageSync('userInfo') || {}
    const openId = userInfo.openid ? userInfo.openid : ''
    uni.request({
      url: `${param.base || ROOT.BASE_URL}gw/${param.url}`,
      data: param.data,
      method: param.method || 'get',
      header: {
        token,
        openId,
        ...param.header
      },
      success: (res) => {
        httpArr.shift()
        console.log(httpArr)
        if (param.loading && httpArr.length === 0) {
          uni.hideLoading()
        }
        console.log(res)
        if (res.data) {
          if (res.data.code === 'S_SYS_000000') {
            resolve(res.data.data)
          } else {
            if (!isHideToast) {
              uni.showToast({
                title: res.data.msg || '返回失败',
                duration: 1500,
                icon: 'none'
              })
            }
            reject(res.data)
          }
        } else {
          uni.showToast({
            title: 'url不存在',
            duration: 1500,
            icon: 'none'
          })
        }
      }
    })
  })
}

export default http
